package com.ruoyi.workflow.listener;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.service.CommonService;
import com.ruoyi.common.core.service.DictService;
import com.ruoyi.common.core.service.UserService;
import com.ruoyi.common.event.MyCustomEvent;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.task.api.Task;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 全局监听-工作流完成消息提醒
 *
 * @author nbacheng
 */

//必须要用 AbstractFlowableEngineEventListener 用FlowableEventListener这个会出现问题，应该是已经完成了
@Component
@RequiredArgsConstructor
public class ProcessCompleteListener extends AbstractFlowableEngineEventListener {

	private final TaskService taskService;
    private final DictService dictService;

    @Resource
    private CommonService commonService;

    @Resource
    private ObjectMapper objectMapper;


    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected UserService userService;

    @Resource
	protected RepositoryService repositoryService;

    @SneakyThrows
    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        System.out.println("进入流程结束监听器……");

        String procInsId = event.getProcessInstanceId();
        HistoricProcessInstance hi = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(procInsId)
                .singleResult();
        //流程发起人id
        String startUserId = hi.getStartUserId();
        SysUser sysUser = userService.getById(startUserId);
        //所有表单内容
        List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(procInsId)
            .list();
        Map<String, Object> map = CollStreamUtil.toMap(list, HistoricVariableInstance::getVariableName,HistoricVariableInstance::getValue);
        //增加发起人部门id字段
        map.put("createDept",sysUser.getDeptId());
        //增加发起人id字段
        map.put("createBy", startUserId);
        //增加流程创建时间
        map.put("createTime",hi.getStartTime());
        //增加流程id
        map.put("processInstanceId",procInsId);

        String name = hi.getProcessDefinitionName();

        // 表单类型
        if (name.contains("资产录入")) {
            map.put("formDataType", 1);
        } else if (name.contains("招标审批")) {
            map.put("formDataType", 2);
        } else if (name.contains("合同管理")) {
            map.put("formDataType", 3);
        } else if (name.contains("租金管理")) {
            map.put("formDataType", 4);
        }
//        userService.getById();
        //通过springboot的订阅监听操作 - 插入到大表内部
        MyCustomEvent myCustomEvent = new MyCustomEvent(this, objectMapper.writeValueAsString(map));
        SpringUtil.getApplicationContext().publishEvent(myCustomEvent);

        List<Task> listtask = taskService.createTaskQuery().processInstanceId(procInsId).active().list();
        String taskId = "";
        if(listtask !=null) {
        	taskId = listtask.get(0).getId();
        }
		String businessKey =  hi.getBusinessKey();
		String deployId = hi.getDeploymentId();
		String category =  "";

        if (StringUtils.isNotEmpty(startUserId)) {
            // TODO:  发送提醒消息
        	if(((ExecutionEntityImpl)event.getEntity()).getVariableInstances().get("category") !=null) {
        		category = ((VariableInstance)((ExecutionEntityImpl)event.getEntity()).getVariableInstances().get("category")).getTextValue();
        	}

        	LoginUser loginUser = commonService.getLoginUser();
            String taskMessageUrl =
                "<a href=" + commonService.getBaseUrl() + procInsId + "?taskId=" + taskId + "&processed=false"
                    + ">点击这个进行查看</a>";
        	String msgContent = "流程任务结束通知" + taskMessageUrl;
            try {
                commonService.sendSysNotice(loginUser.getUserId(), startUserId, "流程任务结束通知", msgContent, Constants.MSG_CATEGORY_1);//setMsgCategory=1是通知
            } catch (Exception e) {
                e.printStackTrace();

            }
        }

        super.processCompleted(event);
    }

    @Override
    protected void taskCompleted(FlowableEngineEntityEvent event) {
        System.out.println("进入taskCompleted监听器……");
        super.taskCompleted(event);
    }

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        System.out.println("进入taskCompleted监听器--onEvent……");
        super.onEvent(flowableEvent);
    }
}
